import React, { useEffect, useState } from 'react'
import './index_v2.less'
// import NavBar from '../../components/Navbar';
// import { GetNickname } from "../../api/mine";
import { Input, Mask, Modal, Toast } from 'antd-mobile'
// import { getRechangeMenu, requestH5Pay } from "../../api/recharge";
import { GetAndroidMenu, ToPay, GetUserInfo, GetIosMenu } from '../../api/mine'
// import { isWechat } from "../../utils/util";
import NavBar from '../../components/Navbar'
import { compareVersions, getAuthentication, getVersion, isIOS } from '../../utils/util'
import appSdk from '../../utils/app_sdk'
import { useNavigate } from 'react-router-dom'

const ua = navigator.userAgent.toLowerCase()
// 1182430
function ExchangeLog() {
  const navigate = useNavigate()
  // const [searchValue, setSearchValue] = useState("");
  const [menu, setMenu] = useState([])
  const [activeId, setActiveId] = useState()
  const [userInfo, setUserInfo] = useState()
  const [type, setType] = useState(1) // 1：支付宝 2：微信
  const [inputMoney, setInputMoney] = useState()

  const [isAppstore, setIsAppstore] = useState(Boolean(getAuthentication('packageChannel')))
  // const [aliPayForm, setAliPayForm] = useState();
  // const [visible, setVisible] = useState(false);

  // const [maskVisible, setMaskVisible] = useState(false);

  const onFocus = () => {
    setActiveId(0)
    scollInput()
  }

  const toPay = () => {
    GetUserInfo().then((result) => {
      setUserInfo({
        ...userInfo,
        ...result.data
      })
      const price = menu?.find((item) => item.id === activeId)?.price || Number(inputMoney) / 10 || ''
      console.log(
        `最新 认证状态 is_idcard: ${result?.data.is_idcard}, is_fase_order: ${result.data.is_fase_order}，已充值金额 ${+result.data.recharge_price}, 待充值 ${price}`
      )
      if (!price) {
        Toast.show({
          content: '请选择要充值的金额',
          maskClickable: false
        })
        return false
      }
      const version = isIOS() ? '2.2.7' : '2.3.2'
      if (compareVersions(getVersion() || '1.0.0', version) !== -1) {
        // 当前版本小于可以拉支付版本
        // 未实名 并且大于500
        if (
          !(Number(result?.data.is_idcard) && result.data.is_fase_order) &&
          +result?.data.recharge_price + Number(price) >= 500 &&
          +result?.data.recharge_status === 0
        ) {
          Toast.show({
            content: '当前账户未实名~',
            maskClickable: false,
            duration: 2000
          })
          const type = Boolean(+result?.data.is_idcard) ? 2 : 1 // 能走到这说明只有两种情况 未实名未刷脸 或者 实名未刷脸
          appSdk('jumpToUserIdentity', type, (result) => {
            console.log('成功回调，拿到的参数是', result)
            if (typeof result === 'string') {
              const data = JSON.parse(result)
              Toast.show({
                icon: data.status === 'success' ? 'success' : 'fail',
                content: data.status === 'success' ? '认证成功' : data?.message || '认证失败',
                duration: 2000
              })
            }
            if (typeof result === 'object') {
              const data = result
              Toast.show({
                icon: data.status === 'success' ? 'success' : 'fail',
                content: data.status === 'success' ? '认证成功' : data?.message || '认证失败',
                duration: 2000
              })
            }
            // Toast.clear()
          })
          return false
        }
      }
      if (Number(price) >= 1) {
        requestPay()
      } else {
        Toast.show({
          content: '最少充值1元',
          maskClickable: false
        })
      }
    })
  }

  useEffect(() => {
    // getRechangeMenu().then((res) => {
    // 	console.log(res);
    // 	setMenu(res.data.goods);
    // });
    requestMenuInfo()
  }, [])

  const requestMenuInfo = (update = true) => {
    Toast.show({
      content: '加载中...',
      icon: 'loading',
      maskClickable: false
    })
    ;(isAppstore ? GetIosMenu() : GetAndroidMenu()).then((res) => {
      GetUserInfo()
        .then((result) => {
          setUserInfo({
            ...res.data,
            ...result.data
          })
          setMenu(res.data.goods)
          if (update) {
            setActiveId(res.data.goods[0].id)
          }
        })
        .finally(() => {
          Toast.clear()
        })
    })
  }

  const requestPay = () => {
    Toast.show({
      icon: 'loading',
      content: '正在支付中，请勿重复提交...',
      maskClickable: false,
      duration: 3000
    })
    if (!isAppstore) {
      ToPay({
        goods_id: activeId ? activeId : null,
        type: type,
        device: /(android)/i.test() ? 'Android' : 'IOS',
        price: activeId ? null : Number(inputMoney) / 10,
        user_id: userInfo.id
      })
        .then((res) => {
          console.log('支付信息', res.data)
          appSdk(type === 1 ? 'aliPay' : 'wechatPay', res.data, (result) => {
            console.log('成功回调，拿到的参数是', result)
            requestMenuInfo(false)
            if (typeof result === 'string') {
              const data = JSON.parse(result)
              Toast.show({
                // icon: data.status === "success" ? "success" : "fail",
                content: data.status === 'success' ? '支付成功' : data?.message || '支付失败'
              })
            }
            if (typeof result === 'object') {
              const data = result
              Toast.show({
                // icon: data.status === "success" ? "success" : "fail",
                content: data.status === 'success' ? '支付成功' : data?.message || '支付失败'
              })
            }
          })
        })
        .finally(() => {
          Toast.clear()
        })
    } else {
      const good_id = menu?.find((item) => item.id === activeId)?.good_id || ''
      appSdk(
        'appStorePay',
        {
          id: activeId,
          good_id
        },
        (result) => {
          Toast.clear()
          console.log('appstore 成功回调，拿到的参数是', result)
          requestMenuInfo(false)
          if (typeof result === 'string') {
            const data = JSON.parse(result)
            Toast.show({
              // icon: data.status === "success" ? "success" : "fail",
              content: data.status === 'success' ? '支付成功' : data?.message || '支付失败'
            })
          }
          if (typeof result === 'object') {
            const data = result
            Toast.show({
              // icon: data.status === "success" ? "success" : "fail",
              content: data.status === 'success' ? '支付成功' : data?.message || '支付失败'
            })
          }
        }
      )
    }
  }

  const scollInput = () => {
    const ua = navigator.userAgent
    const iOS = /iPad|iPhone|iPod/.test(ua)
    const input = document.querySelector('#input')

    setTimeout(() => {
      if (iOS) {
        if (!/OS 11_[0-3]\D/.test(ua)) {
          document.body.scrollTop = document.body.scrollHeight
        }
      } else {
        input.scrollIntoView(false)
      }
    }, 300)
  }

  return (
    <div>
      <NavBar title="我的钱包" />
      <div className="h5-recharge_wrap_v2">
        <div className="cont-wrap">
          <div className="wallet_boxs">
            <div className="in-box yue">
              <div className="tit">
                <span className="t">账户余额</span>
                <span className="tip" onClick={() => navigate(`/record_list?type=dou`)}>
                  余额明细
                </span>
              </div>
              <div className="data">
                <span className="z">{Math.trunc(userInfo?.mizuan || 0)}</span>
                <span className="dot">.{((userInfo?.mizuan || 0) - (userInfo?.mizuan || 0)) * 10}</span>
                <div className="icon"></div>
              </div>
            </div>
            <div className="in-box income">
              <div className="tit">
                <span className="t" onClick={() => navigate('/income')}>
                  账户收益
                </span>
                <span className="tip" onClick={() => navigate('/record_list?type=income')}>
                  收益明细
                </span>
              </div>
              <div className="data">
                <span className="z">{Math.trunc(userInfo?.mibi || 0)}</span>
                <span className="dot">.{userInfo?.mibi ? userInfo?.mibi.toString().split('.')[1] : 0}</span>
              </div>
            </div>
          </div>
          <div className="recharge_list box">
            <div className="tit">充值</div>
            <div className="list_content">
              {menu.map((item) => (
                <div
                  onClick={() => {
                    setActiveId(item.id)
                    setInputMoney('')
                  }}
                  key={item.id}
                  className={`item ${activeId === item.id ? 'active' : ''} ${item.long ? 'long' : 'small'}`}
                >
                  <div className="point">
                    {item?.mizuan} <div className="icon"></div>{' '}
                  </div>
                  <div className="price">{`¥${item?.price}`}</div>
                </div>
              ))}
            </div>
            <div className={`input_warp ${activeId === 0 ? 'active' : ''}`} style={{ display: isAppstore ? 'none' : '' }}>
              <div className="input">
                <Input
                  onFocus={onFocus}
                  onChange={(e) => {
                    setInputMoney(e.replace(/[^\d]/g, ''))
                  }}
                  maxLength={8}
                  value={inputMoney}
                  type="text"
                  placeholder="点击输入其它金额"
                  id="input"
                />
              </div>
              {inputMoney && <div className="income">¥{Number(inputMoney) / 10}</div>}
              <div className="btn" onClick={toPay}>
                充值
              </div>
            </div>
            <div className="pay_way" style={{ display: isAppstore ? 'none' : '' }}>
              <div className="">选择支付方式</div>
              <div className="way">
                <div className="pay_item" onClick={() => setType(2)}>
                  <div className={`select ${type === 2 ? 'selected' : ''}`}></div>
                  <div className="txt">微信支付</div>
                </div>
                <div className="pay_item" onClick={() => setType(1)}>
                  <div className={`select ${type === 1 ? 'selected' : ''}`}></div>
                  <div className="txt">支付宝</div>
                </div>
              </div>
            </div>
            <div className="warn_txt">
              <p>
                严禁未成年人进行充值，请阅读
                <a href={`${window.baseConfig.baseUrl}/protocol/dou_agreement`} style={{ color: '#6167FF', textDecoration: 'none' }}>
                  《{window.baseConfig.package_name}充值协议》
                </a>
              </p>
              {/* <p>请仔细核对用户ID,误充不能退款,谢谢！</p>
						<p>微信额度上限，您可选择支付宝充值！</p>
						<p>请确保支付宝账号所属与{window.baseConfig.package_name}实名认证一致！</p>
						<p style={{ textDecorationLine: "underline" }}>
							如遇诈骗或胁迫等违法行为，请即时报警避免造成财产损失
						</p> */}
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

export default ExchangeLog
